﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Data.OleDb;
using System.ComponentModel;
using System.IO;
using System.Drawing.Drawing2D;
using System.Drawing;
using System.Drawing.Imaging;


namespace sistemaAcademicoFinanceiroEscolas
{
    public partial class definirImagem : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Session["codigoAluno"] = Request["codigoAluno"].ToString();
        }

        protected void btnUp_Click(object sender, EventArgs e)
        {

            SqlConnection conexao = new System.Data.SqlClient.SqlConnection(ConfigurationManager.AppSettings["baseDados"]);
            conexao.Open();

            //inserir registro novo na tabela imagemImovel que conterá o codigo da novaImagem

            string sqlInserir = "update aluno set fotoAluno = 'true' where codigoAluno = " + Session["codigoAluno"].ToString() + "";

            SqlCommand cmdInserir = new SqlCommand(sqlInserir, conexao);
            cmdInserir.ExecuteNonQuery();

            //agora vou resgatar o codigo inserido

            

            //fazer o save as da imagem


            bool extensaoPermitida = false;
            bool arquivoGravado = false;

            string fileName = ArquivoFileUpload.FileName;

            if (ArquivoFileUpload.HasFile)
            {
                string extensaoArquivo = Path.GetExtension(ArquivoFileUpload.FileName);

                string[] extensoesPermitidas = { ".jpg" }; //inserir apenas a extensõa .JPG

       

                for (int i = 0; i < extensoesPermitidas.Length; i++)
                    if (extensoesPermitidas[i] == extensaoArquivo)
                        extensaoPermitida = true;

                if (extensaoPermitida == true)
                {
                    try
                    {
                        ArquivoFileUpload.PostedFile.SaveAs(ConfigurationManager.AppSettings["caminhoImagemMenores"].ToString() + Session["codigoAluno"].ToString() + extensaoArquivo);
                        arquivoGravado = true;
                    }
                    catch (Exception ex)
                    {
                        ErroLabel.ForeColor = Color.Red;
                        ErroLabel.Text = "Ocorreu um problema na tentativa de salvar o arquivo." + ex.ToString();
                        ErroLabel.Visible = true;
                        arquivoGravado = false;
                    }
                }
                else
                {
                    ErroLabel.ForeColor = Color.Red;
                    ErroLabel.Text = string.Format("Tipo de arquivo inválido. Somente sao aceitos arquivos .jpg.", extensoesPermitidas.ToString());
                    ErroLabel.Visible = true;
                }

                if (arquivoGravado)
                {

                    ErroLabel.ForeColor = Color.Blue;
                    ErroLabel.Text = string.Format("Foto definida com sucesso.");
                    ErroLabel.Visible = true;


                    string literalc = "<script language=JavaScript>finalizar();</script>";
                    form1.Controls.Add(new LiteralControl(literalc));
                    



                }
            }

            conexao.Close();

        }

        public static System.Drawing.Image Resize(System.Drawing.Image image, Size size, bool preserveAspectRatio)
        {
            int newWidth;
            int newHeight;
            if (preserveAspectRatio)
            {
                int originalWidth = image.Width;
                int originalHeight = image.Height;
                float percentWidth = (float)size.Width / (float)originalWidth;
                float percentHeight = (float)size.Height / (float)originalHeight;
                float percent = percentHeight < percentWidth ? percentHeight : percentWidth;
                newWidth = (int)(originalWidth * percent);
                newHeight = (int)(originalHeight * percent);
            }
            else
            {
                newWidth = size.Width;
                newHeight = size.Height;
            }

            System.Drawing.Image newImage = new Bitmap(newWidth, newHeight);

            using (Graphics graphicsHandle = Graphics.FromImage(newImage))
            {
                graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphicsHandle.DrawImage(image, 0, 0, newWidth, newHeight);
            }
            return newImage;
        }

    }
}
